import React, { PureComponent } from 'react';
import { Modal, Form, Select, Input, Upload, message, Icon, Button, DatePicker, Row, Col } from 'antd';
import moment from 'moment';
import styles from '../../../components/common/PateoTable/TableList.less';
import { connect } from 'dva';
import { getToken } from '@/utils/utils';
import { getOptAuthHeaders } from '@/utils/common'

const styleRequired = {
  display: 'inline-block',
  marginRight: '4px',
  content: '*',
  fontFamily: 'SimSun',
  lineHeight: '1',
  fontSize: '14px',
  color: '#f5222d',
}
const FormItem = Form.Item;
@connect(state => ({
  menu: state.menu
}))
// @Form.create()
export default class VehicleBatchActiveModal extends PureComponent {
  state = {
    icon: null,
    vinList: '',
    previewVisible: false,
    previewImage: '',
    fileList: [
    ],
    vinFileList: [],
    data: [],
    buttonLoading: false,
    urlVisible: {display: 'none'},
    qualityVisible: { display: 'none' },
    declarerVisible: {},
  };

  componentDidMount() {
    this.props.onRef(this);
  }
  componentWillReceiveProps() {
  }
  getLabel = (lable) => <span><span style={styleRequired}>* </span>{lable}</span>;
  setIcon = (urls) => {
    this.setState({
      icon: urls,
    });
  };
  ok = () => {
    const { form, handleCloseBatchActive, dispatch, page, formValues, qualityUserMap } = this.props;
    this.refs.form.validateFields().then(((fieldsValue)=>{
    console.log('values', fieldsValue)
    this.setState({
      buttonLoading: true,
    });
    const obj = fieldsValue;
    if (fieldsValue.activeType === "6" ) {
      obj.declarer = qualityUserMap.get(fieldsValue.declarerQuality) ? qualityUserMap.get(fieldsValue.declarerQuality) : '';
    } else {
      obj.declarer = fieldsValue.declarerOther;
    }
    obj.url = this.state.icon;
    obj.data = this.state.vinList;
    obj.expiryDate = fieldsValue.expiryDate.format('YYYY-MM-DD');
    obj.batchType = 2; //批量类型，1-单个，2-批量
    dispatch({
      type: 'vehicle/addBatchVehicleActiveApply',
      payload: obj,
      callback: (response) => {
        if (response.code === '200') {
          message.success('批量激活申请上传成功');
          dispatch({
            type: 'vehicle/fetch',
            payload: {
              page: page.current - 1,
              size: page.pageSize,
              ...formValues,
            },
          });
          this.setState({
            icon: null,
            fileList: [],
            vinFileList: [],
            vinList: '',
            buttonLoading: false,
          });
          this.refs.form.resetFields();
          handleCloseBatchActive();
        } else {
          message.error(response.description);
          this.setState({
            buttonLoading: false,
          });
        }
      },
    });
  }))
  };

  checkTemplateFile = (rule, value, callback) => {
    const { urlVisible, icon } = this.state;
    if (!urlVisible.display && !icon) {
      callback('请上传工作联络单');
      return;
    }
    callback();
  }

  checkVinFile = (rule, value, callback) => {
    if (!this.state.vinList) {
      if (value && value.file && value.file.response && value.file.response.error !== 0) {
        callback(value.file.response.message);
        return;
      }
      callback('请上传文件');
      return;
    }
    callback();
  };

  close = () => {
    const { handleCloseBatchActive } = this.props;
    this.setState({
      icon: null,
      fileList: [],
      vinFileList: [],
      vinList: '',
      buttonLoading: false,
      urlVisible: {display: 'none'},
      qualityVisible: { display: 'none' },
      declarerVisible: {},
    });
    this.refs.form.resetFields();
    handleCloseBatchActive();
  }

  disabledDate = (current) => {
    // can not select days before today and today
    return current && (current.valueOf() < (Date.now() - (24 * 60 * 60 * 1000))
      || current.valueOf() > (Date.now() + (364 * 24 * 60 * 60 * 1000)));
  }
  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }

  handleChange = (info) => {
    const { fileList } = info;
    this.setState({ fileList });
    if (info.file.status === 'done') {
      if (fileList[0] && fileList[0].response) {
        this.setIcon(fileList[0].response.url);
        return fileList[0].response.url;
      } else {
        this.setIcon('');
      }
    } else if (info.file.status === 'removed') {
      this.setIcon('');
      // this.props.handleSetData();
    } else if (!info.file.status) {
      this.setState({
        icon: [],
        fileList: [],
      });
    }
  }

  handleBatchChange = (info) => {
    console.log('info', info);
    let { fileList } = info;
    fileList = fileList.slice(-1);
    if (info.file.status === 'done' && info.file.response && info.file.response.error === 0) {
      message.success(`${info.file.name} 上传成功`);
      this.setState({
        vinList: info.file.response.list,
      });
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    } else if (info.file.status === 'done' && info.file.response && info.file.status !== 0) {
      message.error(info.file.response.message);
    } else if (info.file.status === 'removed') {
      this.setState({
        vinList: '',
      });
      const obj = info;
      obj.file = '';
    }
    this.setState({ vinFileList: fileList });
  };

  beforeUpload = (file) => {
    if (file.type === 'image/jpeg' || file.type === 'image/png') {
      if (file.size / 1024 / 1024 > 5) {
        message.error('图片大小不能大于5MB!');
        return false;
      }
      return true;
    } else {
      message.error('请上传JPG或PNG格式图片！');
      return false;
    }
  }

  handleTypeChange = (value) => {
    const {menu: { userProfile }} = this.props;
    // const { currentUser } = this.props;
    this.refs.form.resetFields();
    this.setState({
      icon: null,
      fileList: [],
      vinFileList: [],
      vinList: '',
    });
    if (value === '6') {
      this.setState({
        urlVisible: {display: 'none'},
        qualityVisible: {},
        declarerVisible: { display: 'none' },
      });
      this.refs.form.setFieldsValue({
        expiryDate: moment().add(1, 'days'),
        activeType: value,
      });
    } else {
      this.refs.form.setFieldsValue({
        declarerOther: userProfile.accountName,
        phone: userProfile.userMobile,
        activeType: value,
      });
      this.setState({
        urlVisible: {display: 'none'},
        qualityVisible: { display: 'none' },
        declarerVisible: {},
      });
    }
  }

  onDeclarerChange = (value) => {
    const { phoneMap } = this.props;
    this.refs.form.setFieldsValue({ phone: phoneMap.get(Number(value)) });
  }

  checkDeclarerQuality = (rule, value, callback) => {
    const { qualityVisible } = this.state;
    if (!qualityVisible['display'] && !value) {
      callback('请填写申请人姓名');
      return;
    }
    callback();
  }

  checkDeclarerOther = (rule, value, callback) => {
    const { declarerVisible } = this.state;
    if (!declarerVisible['display'] && !value) {
      callback('请填写申请人姓名');
      return;
    }
    callback();
  }

  renderSimpleForm() {
    const { templateFileUrl, qualityUserOptions } = this.props;
    const { previewVisible, previewImage, fileList,
      vinFileList, buttonLoading, urlVisible, qualityVisible, declarerVisible } = this.state;
    const domain = window.g.url;
    const url = '/common/upload/all';
    const str = `${domain}${url}`;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    const urlbatch = '/common/uploadCheckVin';
    const strbatch = `${domain}${urlbatch}`;
    const props = {
      action: strbatch,
      headers: { OptAuthorization: `${getToken()}`, ...getOptAuthHeaders() },
      onChange: this.handleBatchChange,
      multiple: false,
      showUploadList: { showPreviewIcon: true, showRemoveIcon: true },
    };
    const { activeBatchVisible, typeBatchOptions, label } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 16 },
      },
    };
    return (
      <div>
        <Modal
          title="批量激活"
          // okText="保存"
          visible={activeBatchVisible}
          // onOk={this.ok}
          onCancel={this.close}
          footer={[
            <Button key="back" size="default" onClick={this.close}>
              取消
            </Button>,
            <Button loading={buttonLoading} key="save" type="primary" size="default" onClick={() => this.refs.form.submit()}>
              保存
            </Button>,
          ]}
        >
          <Form
            //hideRequiredMark
            // style={{ marginTop: 12 }}
            ref="form"
            onFinish={this.ok}
          >
            <FormItem
              {...formItemLayout}
              label="激活类型"
              name="activeType"
              rules={[
                { required: true, message: '请选择' },
              ]}
            >
              <Select
                getPopupContainer={triggerNode => triggerNode.parentNode}
                placeholder="请选择" onChange={this.handleTypeChange}>
                {typeBatchOptions}
              </Select>
            </FormItem>
            <FormItem
              style={qualityVisible}
              {...formItemLayout}
              label={this.getLabel('申报人姓名')}
              name="declarerQuality"
              rules={[{ validator: this.checkDeclarerQuality }]}
            >
              <Select
                getPopupContainer={triggerNode => triggerNode.parentNode}
                allowClear
                placeholder="请选择"
                showSearch
                filterOption={(input, option) => option.props.title.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                onChange={this.onDeclarerChange}
              >
                {qualityUserOptions}
              </Select>
            </FormItem>
            <FormItem
              style={declarerVisible}
              {...formItemLayout}
              label={this.getLabel('申报人姓名')}
              name="declarerOther"
              rules={[{ validator: this.checkDeclarerOther }]}
            >
              <Input maxLength="20" placeholder="请填写真实姓名" />
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="电话号码"
              name="phone"
              rules={[{ required: true, message: '电话号码有误', whitespace: true, pattern: /^1[0-9][0-9]\d{8}$/ }]}
            >
              <Input placeholder="请填写电话号码" />
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="截止时间"
              name="expiryDate"
              rules={[
                { required: true, message: '请选择' },
              ]}
            >
              <DatePicker
                getCalendarContainer={trigger => trigger.parentNode}
                style={{ width: '100%' }} disabledDate={this.disabledDate} />
            </FormItem>
            <FormItem
              style={urlVisible}
              {...formItemLayout}
              label={this.getLabel(label)}
              name="url"
              rules={[{ validator: this.checkTemplateFile }]}
            >
              <Upload
                action={str}
                headers={{OptAuthorization: `${getToken()}`, ...getOptAuthHeaders()}}
                listType="picture-card"
                fileList={fileList}
                onPreview={this.handlePreview}
                onChange={this.handleChange}
                beforeUpload={this.beforeUpload}
              >
                {fileList.length >= 1 ? null : uploadButton}
              </Upload>
            </FormItem>
            <FormItem
              {...formItemLayout}
              style={{ marginBottom: '12px' }}
              label={this.getLabel('车辆列表(VIN)')}
              name="listVin"
              rules={[{ validator: this.checkVinFile }]}
            >
              <Upload {...props} fileList={vinFileList}>{
                this.state.vinFileList.length === 0 ? (
                  <Button>
                    <Icon type="upload"/>上传文件
                  </Button>
                ) : null
              }
              </Upload>
            </FormItem>
            {/* <FormItem
              {...formItemLayout}
              style={{ marginBottom: '12px' }}
              label={this.getLabel('车辆列表(VIN)')}
              name="listVin"
              rules={[{ validator: this.checkVinFile }]}
            >
              <Upload {...props} fileList={vinFileList}>
                <Button>
                  <Icon type="upload" />上传文件
                </Button>
              </Upload>
            </FormItem> */}
            <Row>
              <Col md={6} sm={24} />
              <Col md={6} sm={24}>
                {
              templateFileUrl === '' ?
                <a disabled title="点击下载模板文件" >暂无模板下载</a>
                :
                <a href={templateFileUrl} title="点击下载模板文件" >模板文件下载</a>}
              </Col>
            </Row>
          </Form>
        </Modal>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }


  renderForm() {
    return this.renderSimpleForm();
  }
  render() {
    return (
      <div className={styles.tableListForm}>
        {this.renderForm()}
      </div>
    );
  }
}
